import Component from "../Component.js";
import DeviceTimerRefresh from "../shanxi/DeviceTimerRefresh.js"
import ServiceUtils from "../../experience/other/shanxi/ServiceUtils.js"
import KnodeDetail from "./KnodeDetail.js";
import KstationDetail from "./KstationDetail.js";
import MstationDetail from "./MstationDetail.js";
import MstaffDetail from "./StaffDetail.js";
import VcameraDetail from "./VcameraDetail.js";


import Type from "../../experience/db/Type.js";

const Point = ol.geom.Point;
const Feature = ol.Feature;
const Icon = ol.style.Icon;
const Style = ol.style.Style;

import {_toast} from "../../experience/utils/F7.js"

// systemType与souceName的字典对应关系
const DEVICE_SOURCE_DICT = {
    0: Type.M_Station,
    1: Type.K_Station,
    2: Type.K_Node,
    3: Type.V_Camera
}

const DEVICE_TYPE_NAME_DICT = {
    0: '人员分站',
    1: '监控分站',
    2: '测点',
    3: '工业视频'
}

// 沈阳院
export default class DeviceRender extends Component {
    constructor() {
        super();
        const refreshTimer = new DeviceTimerRefresh()
    }

    template() {
        // 设备选择的目录树
        const device_div = `
            <div class="page" id="pannel" style="top: 60px; width: 18vw; height: 87vh;">
                <div class="page-content"></div>
            </div>
        `;

        const device_tree_view = `
            <ul id="deviceTree" class="ztree"></ul>
        `

        // 人员和设备的新的样式下的搜索结果框
        const new_search_dialog = `
            <div id="new-search-dialog" class="new-search-dialog">              
            </div>`

        this.$$("#article").append(device_div);
        this.$$('.page-content').append(device_tree_view)
        this.$$('body').append(new_search_dialog)
        this.$$('#new-search-dialog').hide()
        this.$$("#pannel").hide();
    }

    async control() {
        this.ServiceUtils = new ServiceUtils()
        // 当前的图纸id
        this.currentMetaId = this.utils.getUrlParamer('meta_id')
        this.treeSettings = {
            view: {
                showIcon: false,
                showLine: false,
                fontCss: this.setFontTextColor
            },
            callback: {
                onClick: this.deviceTreeNodeClickCbFun.bind(this),
                onCheck: this.treeOnCheck.bind(this)
            },
            check: {
                chkboxType: {"Y": "", "N": ""},
                enable: true,
                nocheckInherit: true
            }
        }
        this.treeCheckedStatusDict = {
            'm_station': true,
            'k_station': true,
            'camera': true
        }
        // 临时存储的设备从属信息
        this.cache_device_tree_data = {}
        // 设备列表 浮动窗口。当前显示状态
        this.deviceTreeShowStatus = false
        // 点击 图层按钮
        this.$$('#station-select').on('click', () => {
            if (this.deviceTreeShowStatus) {
                this.$$("#pannel").hide();
            } else {
                this.$$("#pannel").show();
            }
            this.deviceTreeShowStatus = !this.deviceTreeShowStatus
            // 改变图层按钮上的 箭头图标
            this.$$("#station-select i").toggleClass("fa-chevron-up", "fa-chevron-down")
        })

        // 将设备详情相关的组件在这里初始化了
        this.initDeviceDetailComponents()

        // 给新的搜索框添加点击事件 用于监听搜索出的列表item的click
        this.$$("#new-search-dialog").on("click", (e) => {
            const item_id = e.target.getAttribute('item_id'), type = e.target.getAttribute('type')
            if (item_id && type) {
                this.deviceLocate(item_id, type)
            }
        })

        // 给新的搜索按钮 绑定change事件
        this.$$("#new-search").on('change', async (e) => {
            const Name = e.target.value
            if (Name.trim() == '') {
                return false
            }
            this.$$("#new-search-dialog").empty()
            const loadingElement = document.createElement('img')
            loadingElement.setAttribute('src', 'assets/images/shanxi/loading.gif')
            this.$$("#new-search-dialog").append(loadingElement)
            this.$$("#new-search-dialog").show();
            // 搜索人员
            const {data: currentStaffList} = await this.api.current_staff_data(this.currentMetaId)
            const staffFilter = this.filter(Name, currentStaffList);
            const fragment = document.createDocumentFragment()
            for (let i = 0; i < staffFilter.length; i++) {
                const div = document.createElement('div')
                div.className = 'searchDialogStaffInfo'
                const propertyInfoDiv1 = document.createElement('div')
                propertyInfoDiv1.className = 'infoPropertyItem'
                propertyInfoDiv1.setAttribute('item_id', staffFilter[i].StaffId)
                propertyInfoDiv1.setAttribute('type', Type.M_Staff)
                propertyInfoDiv1.innerHTML = `
                <span>姓名:${staffFilter[i].Name}</span>
                <span>部门:${staffFilter[i].DepartMent}</span>
                `
                const propertyInfoDiv2 = document.createElement('div')
                propertyInfoDiv2.className = 'infoPropertyItem'
                propertyInfoDiv2.setAttribute('item_id', staffFilter[i].StaffId)
                propertyInfoDiv2.setAttribute('type', Type.M_Staff)
                propertyInfoDiv2.innerHTML = `
                <span>职责:${staffFilter[i].Duty}</span>
                <span>类型:人员</span>
                `
                div.append(propertyInfoDiv1)
                div.append(propertyInfoDiv2)
                fragment.appendChild(div)
            }
            loadingElement.remove()  // 当已经加载出来东西的时候就移除掉 loading
            this.$$("#new-search-dialog").append(fragment);
            // 把搜索到的设备也体现进去
            const searchDeviceList = this.deviceSearch(Name)
            const deviceFragment = document.createDocumentFragment()
            for (let i = 0; i < searchDeviceList.length; i++) {
                const div = document.createElement('div')
                div.className = 'searchDialogStaffInfo'
                const propertyInfoDiv1 = document.createElement('div')
                propertyInfoDiv1.className = 'infoPropertyItem'
                propertyInfoDiv1.setAttribute('item_id', searchDeviceList[i].deviceId)
                propertyInfoDiv1.setAttribute('type', DEVICE_SOURCE_DICT[searchDeviceList[i].type])
                propertyInfoDiv1.innerHTML = `
                <span>名称:${searchDeviceList[i].name}</span>
                <span></span>
                `
                const propertyInfoDiv2 = document.createElement('div')
                propertyInfoDiv2.className = 'infoPropertyItem'
                propertyInfoDiv2.setAttribute('item_id', searchDeviceList[i].deviceId)
                propertyInfoDiv2.setAttribute('type', DEVICE_SOURCE_DICT[searchDeviceList[i].type])
                propertyInfoDiv2.innerHTML = `
                <span>设备类型:${DEVICE_TYPE_NAME_DICT[searchDeviceList[i].type]}</span>
                <span></span>
                `
                div.append(propertyInfoDiv1)
                div.append(propertyInfoDiv2)
                fragment.appendChild(div)
            }
            this.$$("#new-search-dialog").append(fragment);
            this.$$("#new-search-dialog").show();
        })

        // 给新搜索框 绑定input事件
        this.$$("#new-search").on('input', (e) => {
            if (e.target.value.trim() == '') {
                const search = this.$$('#new-search-dialog')
                search.empty()
                search.hide()
            }
        })
        // 关闭 设备目录树加载时候的loading
        this.dataTreeLoadingOpen()
        await this.deviceTreeDataInit()
        // 关闭 设备目录树加载时候的loading
        this.dataTreeLoadingClose()
    }

    // 控制目录树loading的打开
    dataTreeLoadingOpen() {
        const loadingImg = document.createElement('div')
        loadingImg.innerHTML = '<img src="assets/images/shanxi/loading.gif" />'
        loadingImg.style.width = '60px'
        loadingImg.style.height = '60px'
        loadingImg.style.marginLeft = 'auto'
        loadingImg.style.marginRight = 'auto'
        this.$$('#pannel').prepend(loadingImg)
        this.dataTreeLoadImg = loadingImg
    }

    // 控制目录树loading的关闭
    dataTreeLoadingClose() {
        try {
            this.dataTreeLoadImg.remove()
        } catch (e) {
            console.error('不能在没有开启loading图片时，关闭loading')
        }
    }

    // 目录树上的 多选框触发选中或取消的回调函数
    treeOnCheck(event, treeId, Node) {
        switch (Node.name) {
            case '人员定位':
                this.treeCheckedStatusDict['m_station'] = Node.checked
                break
            case '安全监控':
                this.treeCheckedStatusDict['k_station'] = Node.checked
                break
            case '工业视频':
                this.treeCheckedStatusDict['camera'] = Node.checked
                break
            default:
                break
        }
        this.refreshLayerVisibleStatus()
    }

    // 根据 目录树上的多选框状态来觉得 各个图层的 visible状态
    refreshLayerVisibleStatus() {
        const {m_station: m_stationVisible, k_station: k_stationVisible, camera: cameraVisible} = this.treeCheckedStatusDict
        // 人员定位的相关图层
        this.drawer.drawer.m_station.setVisible(m_stationVisible)
        this.drawer.drawer.m_staff.setVisible(m_stationVisible)
        // 安全监控相关的图层
        this.drawer.drawer.k_station.setVisible(k_stationVisible)
        this.drawer.drawer.k_node.setVisible(k_stationVisible)

        // 工业视频相关的 图层
        this.drawer.drawer.v_camera.setVisible(cameraVisible)
    }

    // 设备查找 弹窗里面 搜索获取 设备列表
    deviceSearch(Name) {
        const deviceName = Name
        const filterDeviceArr = []
        const {cameraList, k_station_list, m_station_list} = this.cache_device_tree_data
        const filterCameras = cameraList.filter((camera) => {
            return camera.name.includes(deviceName)
        })
        filterCameras.forEach((camera) => {
            const obj = {
                deviceId: camera.cameraIndexCode,
                type: camera.systemType,
                name: camera.name,
                desc: camera.name
            }
            filterDeviceArr.push(obj)
        })
        const filterMstations = m_station_list.filter((station) => {
            return station.StationName.includes(deviceName) || station.Pos.includes(deviceName)
        })
        filterMstations.forEach((station) => {
            const obj = {
                deviceId: station.StationId,
                type: station.systemType,
                name: station.StationName,
                desc: station.Pos
            }
            filterDeviceArr.push(obj)
        })
        const filterKstations = []
        const filterKnodes = []
        k_station_list.forEach((station) => {
            if (station.name.includes(deviceName) || station.StationPlace.includes(deviceName)) {
                const obj = {
                    deviceId: station.StationID,
                    type: station.systemType,
                    name: station.name,
                    desc: station.StationPlace
                }
                filterKstations.push(obj)
            }
            station.children.forEach((node) => {
                if (node.name.includes(deviceName) || node.NodePlace.includes(deviceName)) {
                    const obj = {
                        deviceId: node.NodeID,
                        type: node.systemType,
                        name: node.name,
                        desc: node.NodePlace
                    }
                    filterKnodes.push(obj)
                }
            })
        })
        const resList = [...filterDeviceArr, ...filterKstations, ...filterKnodes]
        return resList
    }

    //根据人员名称进行人员筛选
    filter(staffName, currentStaffList) {
        const resStaffList = currentStaffList.filter((staff) => {
            return staff.Name.includes(staffName)
        })
        return resStaffList
    }

    async deviceTreeDataInit() {
        this.cache_device_tree_data = await this.ServiceUtils.dataTreeFormat()
        const {m_station_list, k_station_list, cameraList} = this.cache_device_tree_data
        // 专门用于 目录树展示的 人员分站列表
        const tmp_m_stations = []
        m_station_list.forEach((item) => {
            const tmpInstance = {...item}
            delete tmpInstance.children
            tmpInstance.nocheck = true
            tmp_m_stations.push(tmpInstance)
        })
        k_station_list.forEach((item) => {
            item.nocheck = true
        })
        cameraList.forEach((item) => {
            item.nocheck = true
        })
        this.nodes = [
            {
                name: "人员定位", isPos: true, open: true, checked: true, children: tmp_m_stations
            },
            {
                name: "安全监控", isPos: true, open: true, checked: true, children: k_station_list
            },
            {
                name: "工业视频", isPos: true, open: true, checked: true, children: cameraList
            }
        ]
        $(document).ready(() => {
            this.deviceTreeInstance = $.fn.zTree.init($("#deviceTree"), this.treeSettings, this.nodes);
        });

        // 刷新 目录树的数据状态
        this.emitter.on('device-tree-refresh', async () => {
            await this.ztreeRefresh()
        })
    }

    setFontTextColor(treeId, treeNode) {
        if(treeNode.level == 0) {
            return {color: "white"}
        }
        return treeNode.isPos ? {color: "green"} : {color: "red"};
    }

    async ztreeRefresh() {
        const {m_station_list, k_station_list, cameraList} = await this.ServiceUtils.dataTreeFormat()
        const copy_m_station_list = []
        m_station_list.forEach((item) => {
            const tmp = {...item}
            delete tmp.children
            tmp.nocheck = true
            copy_m_station_list.push(tmp)
        })
        k_station_list.forEach((item) => {
            item.nocheck = true
        })
        cameraList.forEach((item) => {
            item.nocheck = true
        })
        console.log('当前的 treeCheckedStatusDict', this.treeCheckedStatusDict)
        this.nodes = [
            {
                name: "人员定位",
                isPos: true,
                open: true,
                checked: this.treeCheckedStatusDict['m_station'],
                children: copy_m_station_list
            },
            {
                name: "安全监控",
                isPos: true,
                open: true,
                checked: this.treeCheckedStatusDict['k_station'],
                children: k_station_list
            },
            {
                name: "工业视频",
                isPos: true,
                open: true,
                checked: this.treeCheckedStatusDict['camera'],
                children: cameraList
            }
        ];
        $.fn.zTree.init($("#deviceTree"), this.treeSettings, this.nodes);
    }

    // 设备定位
    deviceLocate(deviceId, sourceName) {
        const source = this.drawer.source(sourceName)
        const features = source.getFeatures()
        const targetFeature = features.find((f) => {
            return f.get('device_id') == deviceId
        })
        try {
            const coordinate = targetFeature.getGeometry().getCoordinates()
            this.drawer.map.getView().setCenter(coordinate);
            // 创建一个临时的矩形框 标记出 当前的view中心
            const tmpImg = new Icon({
                src: 'assets/images/shanxi/rectangle.png',
                scale: 0.25
            })
            const recStyle = new Style({
                image: tmpImg
            })
            const rectangleFeature = new Feature()
            rectangleFeature.setGeometry(new Point(coordinate))
            rectangleFeature.setStyle(recStyle)
            source.addFeature(rectangleFeature)
            const tmpTimer = setTimeout(() => {
                source.removeFeature(rectangleFeature)
                clearTimeout(tmpTimer)
            }, 1500)
            return true
        } catch (e) {
            _toast('当前分站或设备还没有被添加位置，请先添加位置')
            return false
        }
    }

    // 目录树 触发设备点击。
    deviceTreeNodeClickCbFun(event, treeId, treeNode) {
        console.log('treeNode', treeNode)
        if (treeNode.level == 0) {
            // 第一层级 直接跳过
            return
        }
        const sourceName = DEVICE_SOURCE_DICT[treeNode.systemType]
        const device_id = treeNode.cameraIndexCode ?? treeNode.NodeID ?? treeNode.StationID ?? treeNode.StationId
        this.deviceLocate(device_id, sourceName)
    }

    // 各类设备 详情弹窗组件的使用
    initDeviceDetailComponents() {
        new KnodeDetail()
        new KstationDetail()
        new MstationDetail()
        new MstaffDetail()
        new VcameraDetail()
    }

}